//
//  ZLSessionListViewController.m
//  ZLYoYoIM_Example
//
//  Created by 赵磊 on 2021/1/15.
//  Copyright © 2021 itzhaolei. All rights reserved.
//

#import "ZLSessionListViewController.h"
#import "ZLSessionViewController.h"
#import "ZLNavigationBarHeader.h"
#import "ZLSessionListCell.h"
#import <NIMKit/NIMKitUtil.h>
#import <UIImageView+WebCache.h>
#import <NIMKit/NIMKitInfoFetchOption.h>
#import "UIImage+ZLIMCustom.h"
#import "NIMAvatarImageView+ZLCustom.h"

@implementation ZLSessionListCellModel

@end

@interface ZLSessionListViewController ()

///导航条
@property (nonatomic,weak) ZLNavigationBar *navBar;
///导航条
@property (nonatomic,weak) UIView *tableHeaderView;
///角标控件
@property (nonatomic,strong) NSMutableArray <UILabel *> *iconBadgeNumberLabels;

@end

@implementation ZLSessionListViewController

- (void)viewDidLoad {
    self.iconBadgeNumberLabels = [NSMutableArray new];
    [super viewDidLoad];
    [self registerAction];
    self.iconBadgeNumbers = @[@"0",@"0",@"0",@"0"];
    [self configDefaultOfficialAssistantModel];
}

#pragma mark - Lazy
- (ZLNavigationBar *)navBar {
    if (!_navBar) {
        ZLNavigationBar *navBar = [ZLNavigationBar navigationBar];
        navBar.title = @"消息";
        [navBar.actionBar.rightMainItem setImage:[UIImage imageNamedInIM:@"消息_设置"] forState:UIControlStateNormal];
        [self.view addSubview:navBar];
        _navBar = navBar;
    }
    return _navBar;
}

#pragma mark - Set
- (void)setIconBadgeNumbers:(NSArray *)iconBadgeNumbers {
    _iconBadgeNumbers = iconBadgeNumbers;
    if (iconBadgeNumbers.count != self.iconBadgeNumberLabels.count) {
        NSLog(@"ERROR:角标数量和控件数量不一致，请检查后重新尝试赋值。ZLSessionListViewController.CLASS");
        return;
    }
    for (UILabel *label in self.iconBadgeNumberLabels) {
        label.hidden = YES;
        NSString *number = self.iconBadgeNumbers[[self.iconBadgeNumberLabels indexOfObject:label]];
        if (![number isEqualToString:@"0"]) {
            label.hidden = NO;
            label.text = number;
        }
    }
}

- (void)setTableView:(UITableView *)tableView {
    super.tableView = tableView;
    [self configTableView];
}
#pragma mark - Action
- (void)configDefaultOfficialAssistantModel {
    ZLSessionListCellModel *model = [ZLSessionListCellModel new];
    model.title = @"又友官方";
    model.content = @"系统提示消息！为您发送专属信息...";
    self.officialAssistantModel = model;
}
- (void)configTableView {
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = NO;
    //ios11 适配
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
    }
    BOOL isBangDevice = NO;
    if (@available(iOS 11.0, *)) {
        isBangDevice = UIApplication.sharedApplication.delegate.window.safeAreaInsets.bottom;
    }
    CGFloat ZL_Navigation_Height = isBangDevice ? 84.0 : 64.0;
    CGFloat homeBarHeight = isBangDevice ? 30.0 : 0.01;
    self.tableView.contentInset = UIEdgeInsetsMake(ZL_Navigation_Height, 0, homeBarHeight, 0);
    
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 109.0)];
    CGFloat width = 60.0;
    CGFloat edgeSpace = 25.0;
    CGFloat space = (UIScreen.mainScreen.bounds.size.width - width * 4 - edgeSpace * 2) / 3.0;
    NSArray *imageNames = @[@"点赞",@"评论",@"报名",@"钱包通知"];
    for (NSInteger index = 0; index < imageNames.count; index++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(edgeSpace + (space + width) * index, 15.0, width, width + 7.0 + 14.0)];
        [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(functionActions:)]];
        [tableHeaderView addSubview:view];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((width - 44.0) / 2.0, 0, 44.0, 44.0)];
        imageView.image = [UIImage imageNamedInIM:imageNames[index]];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [view addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((width - (width - 44.0) / 2.0) - 10.0, -2.0, 20.0, 20.0)];
        label.font = [UIFont boldSystemFontOfSize:10.0];
        label.textColor = UIColor.whiteColor;
        label.backgroundColor = UIColor.redColor;
        label.layer.cornerRadius = CGRectGetHeight(label.frame) / 2.0;
        label.layer.masksToBounds = YES;
        label.layer.borderColor = UIColor.whiteColor.CGColor;
        label.layer.borderWidth = 2.0;
        label.textAlignment = NSTextAlignmentCenter;
        label.hidden = YES;
        [view addSubview:label];
        [self.iconBadgeNumberLabels addObject:label];
        
        label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView.frame) + 7.0, width, 14.0)];
        label.font = [UIFont systemFontOfSize:14.0];
        label.textColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
        label.text = imageNames[index];
        label.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label];
        
    }
    
    CALayer *layer = [CALayer layer];
    layer.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0].CGColor;
    layer.frame = CGRectMake(0, 103.0, UIScreen.mainScreen.bounds.size.width, 6.0);
    [tableHeaderView.layer addSublayer:layer];
    
    self.tableView.tableHeaderView = tableHeaderView;
}
- (void)registerAction {
    __weak typeof(self)weakSelf = self;
    self.navBar.actionBar.rightMainItem.click = ^{
        [weakSelf clickSetup];
    };
}
- (void)functionActions:(UITapGestureRecognizer *)tap {
    NSInteger index = [tap.view.superview.subviews indexOfObject:tap.view];
    [self clickTopFunction:index];
}

#pragma mark - Overload
- (void)onTouchAvatar:(id)sender{
    UIView *view = [sender superview];
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = view.superview;
    }
    UITableViewCell *cell  = (UITableViewCell *)view;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NIMRecentSession *recent = self.recentSessions[indexPath.row];
    [self onSelectedAvatar:recent atIndexPath:indexPath];
}
- (void)onSelectedRecent:(NIMRecentSession *)recent atIndexPath:(NSIndexPath *)indexPath {
    if (![self isAllowLookIMDetailsWithIMID:recent.session.sessionId]) {
        NSLog(@"改用户查看聊天信息被阻断操作");
        return;
    }
    [self lookIMDetailsWithRecent:recent];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.recentSessions.count + 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZLSessionListCell * cell = [ZLSessionListCell reuseCell:tableView];
    NIMRecentSession *recent = nil;
    if (indexPath.row) {
        recent = self.recentSessions[indexPath.row - 1];
        cell.titleLabel.text = [self nameForRecentSession:recent];
        NIMKitInfoFetchOption *option = [[NIMKitInfoFetchOption alloc] init];
        option.session = recent.session;
        [cell.iconImageView setAvatarBySession:recent.session];
        cell.subTitleLabel.attributedText  = [self contentForRecentSession:recent];
        cell.timeLabel.text = [self timestampDescriptionForRecentSession:recent];
        NSString *badgeNumber = [NSString stringWithFormat:@"%ld",recent.unreadCount];
        cell.badgeLabel.hidden = YES;
        if (![badgeNumber isEqualToString:@"0"]) {
            cell.badgeLabel.text = badgeNumber;
            cell.badgeLabel.hidden = NO;
        }
    }else {
        cell.titleLabel.text = self.officialAssistantModel.title;
        [cell.iconImageView setImageWithName:@"系统消息图"];
        cell.subTitleLabel.text = self.officialAssistantModel.content;
        cell.timeLabel.text = self.officialAssistantModel.time;
        cell.badgeLabel.text = self.officialAssistantModel.badgeNumber;
    }
    
    __weak typeof(self)weakSelf = self;
    cell.clickIcon = ^{
        NIMRecentSession *recent = weakSelf.recentSessions[indexPath.row - 1];
        NSString *currentIMID = recent.session.sessionId;
        [weakSelf clickIconWithIMID:currentIMID];
    };
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!indexPath.row) {
        [self clickOfficialAssistant];
        return;
    }
    NIMRecentSession *recentSession = self.recentSessions[indexPath.row - 1];
    [self onSelectedRecent:recentSession atIndexPath:indexPath];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70.f;
}
- (NSString *)nameForRecentSession:(NIMRecentSession *)recent {
    return [super nameForRecentSession:recent];
}

#pragma mark - WaitingCall
- (void)clickIconWithIMID:(NSString *)IMID {
    NSLog(@"点击头像已响应，被点击的IMID为:%@",IMID);
}
- (void)clickSetup {
    NSLog(@"设置按钮已响应");
}
- (void)clickTopFunction:(NSInteger)index {
    NSLog(@"点击顶部功能已响应，被点击的索引为:%ld",index);
}
- (BOOL)isAllowLookIMDetailsWithIMID:(NSString *)IMID {
    return YES;
}
- (void)lookIMDetailsWithRecent:(NIMRecentSession *)recent {
    ZLSessionViewController *vc = [[ZLSessionViewController alloc] initWithSession:recent.session];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)clickOfficialAssistant {
    NSLog(@"官方助理已响应");
}

@end
